package org.iartisan.thought.web.controller;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.iartisan.runtime.utils.StringUtils;
import org.iartisan.runtime.web.WebR;
import org.iartisan.runtime.web.contants.ReqContants;
import org.iartisan.runtime.web.utils.WebUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * <p>
 * login
 *
 * @author King
 * @since 2017/12/15
 */
@Controller
public class LoginController extends BaseController {

    @Autowired
    private Producer producer;

    @GetMapping(value = "captcha")
    public void captcha(HttpServletResponse response) throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        //生成文字验证码
        String text = producer.createText();
        //生成图片验证码
        BufferedImage image = producer.createImage(text);
        //保存到shiro session
        WebUtil.getShiroSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, text);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        out.flush();
    }


    @GetMapping(value = ReqContants.REQ_LOGIN)
    public String index() {
        return "login";
    }


    @ResponseBody
    @PostMapping(value = ReqContants.REQ_AUTHENTICATE)
    public WebR authenticate(String email, String pass, String vercode) {
        WebR r = new WebR();
        //判断验证码是否正确
        if (StringUtils.isEmpty(vercode) ||
                !WebUtil.getShiroSession().getAttribute(Constants.KAPTCHA_SESSION_KEY).toString().equals(vercode)) {
            r.isError("验证码错误");
            return r;
        }
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(email, pass);
        try {
            subject.login(token);
            r.setMessage("/index");
        } catch (AuthenticationException e) {
            r.isError(e.getMessage());
            return r;
        }
        return r;
    }

    @GetMapping(value = ReqContants.REQ_LOGOUT)
    public String logout() {
        WebUtil.getShiroSubject().logout();
        return "redirect:index";
    }

}
